package com.matrix.im.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import io.netty.buffer.PooledByteBufAllocator;

/**
 * @author 有点甜
 * @since 2025/8/6
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class NettyServer implements CommandLineRunner {

    @Value("${netty.port:8090}")
    private int port;

    private final IMChannelInitializer imChannelInitializer;


    private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);

    private final EventLoopGroup workerGroup = new NioEventLoopGroup();

    @Override
    public void run(String... args) {
        new Thread(() -> {
            try {
                ServerBootstrap bootstrap = new ServerBootstrap();
                
                bootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                        .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                        .childOption(ChannelOption.SO_KEEPALIVE, true)
                        .option(ChannelOption.SO_BACKLOG, 128)
                        .childOption(ChannelOption.SO_KEEPALIVE, true)
                        .childHandler(imChannelInitializer);

                log.info("Netty IM Server is starting on port: {}", port);
                
                ChannelFuture future = bootstrap.bind(port).sync();
                
                future.channel().closeFuture().sync();

            } catch (InterruptedException e) {
                log.error("Netty IM Server was interrupted.", e);
                Thread.currentThread().interrupt();
            } finally {
                shutdown();
            }
        }, "netty-im-server-thread").start();
    }

    @PreDestroy
    public void shutdown() {
        log.info("Shutting down Netty IM Server...");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        log.info("Netty IM Server shut down gracefully.");
    }
}
